<template>
  <div class="dataInspect">
    <div style="flex: 1">
      <el-card shadow="never">
        <div slot="header" style="display: flex;align-items: center;justify-content: space-between;">
          <n-tab :options="tabOptions" @click="tabCheckHandler"/>
          <div class="ha-top">
            <el-select v-model="selectFormModel.verifyTimes" class="verify-times-select"
                       style="margin-right: 10px;" size="mini" @change="onVerifyTimesChange">
              <el-option
                  v-for="item in verifyTimesList"
                  :key="item.verifyTimes"
                  :label="item.verifyTimeLabel"
                  :value="item.verifyTimes">
              </el-option>
            </el-select>
          </div>
        </div>
        <div>
          <el-row :gutter="10">
            <el-col :span="5">
              <el-card shadow="never">
                <div class="area-title">核查区域</div>
                <div style="margin-top: 10px;">
                  <el-tree :data="subAreaList" :props="defaultProps" default-expand-all>
                    <template slot-scope="{ data }" class="custom-tree-node">
                      <span style="font-size: 14px;color: #006400">{{ data.label }} {{data.code}}</span>
                    </template>
                  </el-tree>
                </div>
              </el-card>
            </el-col>
            <el-col :span="19">
              <el-card shadow="never">
                <div class="ha-top" style="border-bottom: black">
                  <n-title title="核查统计列表"/>
                  <div>
                    <el-button size="small" plain type="primary" @click="statsDialogVisible = true" :disabled="!(verifyStatsInfo.verifyState =='2')">核查统计</el-button>
                    <el-button size="small" plain type="primary" @click="generateSampleReport" :disabled="verifyStatsInfo.verifyState !='3' || verifyStatsInfo.reportTag">生成报告</el-button>
                    <el-button size="small" plain type="primary" @click="feedbackDialogVisible = true" :disabled="!(verifyStatsInfo.verifyState =='3')">反馈采集</el-button>
                    <el-button size="small" plain type="primary" @click="downloadSampleReport" :disabled="!verifyStatsInfo.reportTag" :loading="downloadReportLoading">下载报告</el-button>
                    <el-dialog title="提示" :visible.sync="statsDialogVisible">
                      <span>统计前请确认是否全部上报，统计后不可撤销，并且只能统计一次，确认是否统计？</span>
                      <span slot="footer" class="dialog-footer">
                          <el-button @click="statsDialogVisible = false">取 消</el-button>
                          <el-button type="primary" @click="sampleDataCheck">确 定</el-button>
                      </span>
                    </el-dialog>
                    <el-dialog title="提示" :visible.sync="feedbackDialogVisible">
                      <span>核查结果反馈采集后，请根据标错信息进行整改</span>
                      <span slot="footer" class="dialog-footer">
                          <el-button @click="feedbackDialogVisible = false">取 消</el-button>
                          <el-button type="primary" @click="feedbackSampleResult">确 定</el-button>
                      </span>
                    </el-dialog>
                  </div>
                </div>
                <div class="ha-top" style="padding: 20px 150px">
                  <div><span style="font-size: 20px">整体差错率：</span>
                    <span v-if="verifyStatsInfo.resultState == '1'" style="color: green">{{verifyStatsInfo.errorRatio ? verifyStatsInfo.errorRatio : 0}}%</span>
                    <span v-else style="color: red">{{verifyStatsInfo.errorRatio ? verifyStatsInfo.errorRatio : 0}}%</span>
                  </div>
                  <div><span style="font-size: 20px">检查结果：</span>
                    <span v-if="verifyStatsInfo.resultState == '1'" style="color: green">通过</span>
                    <span v-else style="color: red">{{verifyStatsInfo.resultState == '0' ? '未通过' : '未统计'}}</span>
                  </div>
                </div>
                <data-table
                    :api="selectVerifyStatsList"
                    ref="dataTable"
                    :options="options"
                    :columns="columns"
                    :operates="operates"
                    :query="selectFormModel"
                ></data-table>
              </el-card>
            </el-col>
          </el-row>
        </div>

      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import {Component, Ref, Vue} from 'vue-property-decorator';
import DataTable from "@/components/DataTable/DataTable.vue";
import NTab from "@/components/NTab.vue";
import NTitle from "@/components/NTitle.vue";
import AreaTree from "@/views/dataShow/components/AreaTree.vue";
import { userAreaTreeSelectData} from "@/api/area"
import {
  queryWorkVerifyTimes,
  queryVerifyWorkList,
} from "@/api/verifyWork";
import {
  queryVerifyStatsInfo,
  selectVerifyStatsList,
  sampleDataCheck,
  generateSampleReport,
  feedbackSampleResult
} from "@/api/verifyStats";
import storeUtils from "@/utils/storeUtils";
import {Message,Loading} from "element-ui";

@Component({
  methods: {queryVerifyStatsInfo, selectVerifyStatsList},
  components: {NTitle, AreaTree, NTab, DataTable}
})
export default class verifyStats extends Vue {
  @Ref('dataTable') private dataTable: any;
  verifyTimesList: any = [];
  subAreaList: any = [];
  areaInfo:any = {
    areaCode:''
  }
  tabOptions: any = [];
  areaName = '区县'
  statsDialogVisible = false;
  exportFormLoading = false;
  feedbackDialogVisible = false;
  downloadReportLoading = false;
  verifyStatsInfo:any = {
    errorRatio:0,
    resultState:undefined,
    verifyState:'2',
    reportFileId:undefined,
    reportTag:undefined
  };

  //核查统计
  sampleDataCheck() {
    let loadingInstance = Loading.service({fullscreen: true, background: 'rgba(0, 0, 0, 0.7)'});
    sampleDataCheck(this.selectFormModel).then(res=>{
      Message.success("核查统计成功");
      this.statsDialogVisible = false;
      this.queryVerifyStatsInfo();
    }).catch(err=>{
      Message.error("核查统计失败");
    }).finally(()=>{
      loadingInstance?.close();
    })
  }

  //生成报告
  generateSampleReport() {
    let loadingInstance = Loading.service({fullscreen: true, background: 'rgba(0, 0, 0, 0.7)'});
    generateSampleReport(this.selectFormModel).then(res=>{
      Message.success("生成报告成功");
      this.queryVerifyStatsInfo()
    }).catch(err=>{
      Message.error("生成报告失败");
    }).finally(()=>{
      loadingInstance?.close();
    })
  }

  //下载报告
  downloadSampleReport() {
    this.downloadReportLoading = true;
    const link = document.createElement('a');
    link.href = process.env.VUE_APP_BASE_API +'/resources/file/'+this.verifyStatsInfo.reportFileId;
    link.setAttribute('download','test.doc');
    link.click();
    link.remove();
    this.downloadReportLoading = false;
  }

  //反馈采集
  feedbackSampleResult() {
    let loadingInstance = Loading.service({fullscreen: true, background: 'rgba(0, 0, 0, 0.7)'});
    feedbackSampleResult(this.selectFormModel).then(res=>{
      Message.success("反馈采集成功");
      this.feedbackDialogVisible = false;
      this.queryVerifyStatsInfo()
    }).catch(err=>{
      Message.error("反馈采集失败");
    }).finally(()=>{
      loadingInstance?.close();
    })
  }

  defaultProps:any = {
    children: 'children',
    label: 'label'
  }

  //调查任务切换
  tabCheckHandler(data) {
    this.queryVerifyTimes(data.item.id);
    this.selectFormModel.workId = data.item.id;
  }

  // table 的参数
  options: any = {
    stripe: true, // 是否为斑马纹 table
    loading: false, // 是否添加表格loading加载动画
    highlightCurrentRow: true, // 是否支持当前行高亮显示
    multipleSelect: false, // 是否支持列表项选中功能
    page: false
  };

  //类别筛选-按钮操作组
  operates: any = {
    title: '操作',
    width: 'auto',
    fixed: 'right',
    list: [
      {
        label: '查看',
        type: 'text',
        icon: 'el-icon-view',
        plain: true,
        disabled: (index: any, row: any) => {
          return false;
        },
        method: (index: any, row: any) => {
          this.$router.push({
            path: '/verify/verifyStatsDetail',
            query: {
              workId: this.selectFormModel.workId,
              verifyTimes: this.selectFormModel.verifyTimes,
              areaCode: this.areaInfo.areaCode
            }
          });
        }
      }
    ]
  };
  //查询参数
  selectFormModel: any = {
    workId: undefined,
    verifyTimes: undefined
  };

  //区域筛选-列
  columns: any = [
    {label: '区域', prop: 'areaName', align:'center'},
    {label: '调查总量', prop: 'workTotal', width: '80', align:'center'},
    {label: '抽样数量', prop: 'verifyCount', width: '80', align:'center'},
    {label: '核查调查指标数量', prop: 'verifyDataTargetTotal', width: '140', align:'center'},
    {label: '错误调查指标数量', prop: 'verifyErrorTargetTotal', width: '140', align:'center'},
    {label: '遗漏对象数量', prop: 'missDataCount', width: '100', align:'center'},
    {label: '差错率', prop: 'errorRate', width: '80', align:'center', formatter: function (row: any) {
          return row.errorRate+'%';
      }},
  ];

  onSearch() {
    this.dataTable.refresh();
  }

  //筛选次数修改
  onVerifyTimesChange(): void {
    this.queryVerifyStatsInfo();
    this.onSearch()
  }


  //查询调查任务抽样次数
  queryVerifyTimes(workId) {
    queryWorkVerifyTimes({workId: workId}).then(res => {
      if (res.data) {
        this.verifyTimesList = res.data
        this.selectFormModel.verifyTimes = res.data[0].verifyTimes
        this.queryVerifyStatsInfo()
        this.onSearch()
      }
    })
  }

  /**
   * 查询大类统计描述
   */
  queryVerifyStatsInfo() {
    queryVerifyStatsInfo({
      workId: this.selectFormModel.workId,
      verifyTimes: this.selectFormModel.verifyTimes
    }).then(res => {
      if (res.data) {
        this.verifyStatsInfo = res.data
        this.verifyStatsInfo.reportTag = !!res.data.reportFileId;
      }
    })
  }

  //导出数据核查数据
  async exportVerifyData() {
    this.exportFormLoading = true;
  }

  mounted() {
    var dept = storeUtils.getStorageS(storeUtils.CONST.departInfo)
    if (dept) {
      this.areaInfo.areaCode = dept.areaCode
      if (dept.areaLevel == '1') {
        this.areaName = '地市'
      } else if (dept.areaLevel == '0') {
        this.areaName = '省'
      }
    }

    //调查任务
    queryVerifyWorkList().then(res => {
      if (res.data) {
        res.data.forEach(wd => {
          this.tabOptions.push({label: wd.name, id: wd.id});
        })
        this.tabCheckHandler({item: this.tabOptions[0]});
      }
    });
    //获取登录人的下级区域列表
    userAreaTreeSelectData().then(res=> {
      if (res.data) {
        this.subAreaList = res.data
      }
    })
  }
}
</script>
<style lang="scss" scoped>
.dataInspect {
  display: flex;
  gap: 10px;

  .ha-top {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .radio-t {
      display: flex;
      align-items: center;
      gap: 6px;

      span {
        font-size: 14px;
      }
    }
  }
}

.m-b10 {
  height: 40px;
}
.area-title {
  width: 100%;
  background-image: linear-gradient(to right, #99D5CFFF, white);
  padding-left: 20px;
  color: #5b9a8e;
  font-weight: bold;
  font-size: 14px;
  padding-bottom: 6px;
  cursor: pointer;
  border-left: 2px solid #5b9a8e;
}
.verify-times-select {
  .el-input__inner {
    color: #5b9a8e;
    font-size: 18px;
  }
}
</style>
